package com.chijun.mform.create.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.alibaba.fastjson.JSONObject;
import com.chijun.mform.FormBuilder;
import com.chijun.mform.R;
import com.chijun.mform.create.IWaitResult;
import com.chijun.mform.create.field.Field;
import com.chijun.mform.create.mode.FormGroup;
import com.chijun.mform.create.mode.FormIcon;
import com.example.ccj.b.a.BaseActivity;
import com.example.ccj.u.JsonUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.server.MyObserver;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 选择创建表单的类型
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/11/12 15:28
 */
public class FormSelectCreateTypeActivity extends BaseActivity {


    public static final int FORM_TYPE_DATA = 0;         //数据类表
    public static final int FORM_TYPE_PROCESS = 1;      //审批类表

    LinearLayout mLlCreateDataForm,mLlCreateProcessForm;

    @Override
    public void initData(@Nullable Bundle bundle) {

        mLlCreateDataForm.setOnClickListener(openCreateDataFormActivity);
        mLlCreateProcessForm.setOnClickListener(openCreateProcessFormActivity);

        showLoadingDialog();
        FormBuilder.getInstance().getCreateFormConfig(new IWaitResult() {
            @Override
            public void onResult(String val) {
                Observable.create(new ObservableOnSubscribe<String>() {
                            @Override
                            public void subscribe(ObservableEmitter<String> e) throws Exception {
                                if (StringUtils.isEmpty(val)) {
                                    e.onError(new RuntimeException("未获取到配置信息"));
                                    return;
                                }
                                analysisData(val);
                                e.onNext("");
                            }}).subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new MyObserver<String>() {
                            @Override
                            public void onNext(String s) {
                                dismissLoadingDialog();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                dismissLoadingDialog();
                                showErrorDialog("表单加载失败：" +e.getMessage());
                                LogUtils.e("未获取到配置信息");
                            }
                        });
            }

            @Override
            public void onError(String error) {
                dismissLoadingDialog();
                showErrorDialog("表单加载失败：" +error);
            }
        });

    }

    /**
     * 解析配置
     * @param val 配置数据
     */
    private void analysisData(String val){

        JSONObject jsonObject = JSONObject.parseObject(val);
        //字段配置
        if (jsonObject.containsKey("field")) {
            String fieldStr = jsonObject.getString("field");
            if (!StringUtils.isEmpty(fieldStr)) {
                List<Field> listBean = JsonUtils.toListBean(fieldStr, Field.class);
                if (listBean != null) {
                    Field[] fields = new Field[listBean.size()];
                    for (int i = 0; i < listBean.size(); i++) {
                        fields[i] = listBean.get(i);
                    }
                    FormBuilder.getInstance().setFields(fields);
                }
            }
        }

        //表单类型配置
        if (jsonObject.containsKey("group")) {
            String fieldStr = jsonObject.getString("group");
            if (!StringUtils.isEmpty(fieldStr)) {
                List<FormGroup> listBean = JsonUtils.toListBean(fieldStr, FormGroup.class);
                FormBuilder.getInstance().setFormGroupList(listBean);
            }
        }

        //日期格式配置
        if (jsonObject.containsKey("time")) {
            String fieldStr = jsonObject.getString("time");
            if (!StringUtils.isEmpty(fieldStr)) {
                List<String> listBean = JsonUtils.toListBean(fieldStr, String.class);
                FormBuilder.getInstance().setTimeType(listBean);
            }
        }


        //表单图标
        List<FormIcon> formIconList = new ArrayList<>();
        if (jsonObject.containsKey("icon")) {
            String fieldStr = jsonObject.getString("icon");
            if (!StringUtils.isEmpty(fieldStr)) {
                formIconList = JsonUtils.toListBean(fieldStr, FormIcon.class);
            }
        } else {
            for (int i = 1; i < 76; i++) {
                FormIcon formIcon = new FormIcon(i,"https://form-icon-1302729481.cos.ap-beijing.myqcloud.com/icon_" + i + ".png");
                formIconList.add(formIcon);
            }
        }
        FormBuilder.getInstance().setFormIconList(formIconList);
    }


    @Override
    public void initView(@Nullable Bundle bundle, @Nullable View view) {
        mLlCreateDataForm = findViewById(R.id.create_data_form);
        mLlCreateProcessForm = findViewById(R.id.create_process_form);
    }

    @Override
    public int initContentView() {
        showTopBar("选择创建方式");
        return R.layout.activity_create_form;
    }

    /**
     * 打开创建数据表单的activity
     */
    View.OnClickListener openCreateDataFormActivity = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(FormSelectCreateTypeActivity.this, CreateFormActivity.class);
            intent.putExtra("form_type",FORM_TYPE_DATA);
            startActivity(intent);
        }
    };

    /**
     * 打开创建流程表单的activity
     */
    View.OnClickListener openCreateProcessFormActivity = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(FormSelectCreateTypeActivity.this, CreateFormActivity.class);
            intent.putExtra("form_type",FORM_TYPE_PROCESS);
            startActivity(intent);
        }
    };


    @Override
    public void addMenuProvider(@NonNull MenuProvider provider, @NonNull LifecycleOwner owner, @NonNull Lifecycle.State state) {

    }
}